package com.szholly.plug.form.word;

//import java.io.BufferedWriter;
//import java.io.ByteArrayOutputStream;
import java.io.File;
//import java.io.FileOutputStream;
import java.io.IOException;
//import java.io.OutputStream;
//import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
//import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

//import com.szholly.utils.common.web.IRealPathResolver;
//import com.szholly.utils.util.DateUtils;
import com.szholly.data.general.RowBase;

//import freemarker.cache.ClassTemplateLoader;
//import freemarker.cache.MultiTemplateLoader;
//import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * word操作类
 * 
 * @author CHENXU
 * 
 */
@Controller
public class WordController {

//	@Autowired
//	private IRealPathResolver realPathResolver;
	
	/**
	 * 导出word文档
	 * 
	 * @param dataMap
	 * @param flt
	 * @throws IOException 
	 */
	@RequestMapping(value = "/word/export")
	public void exportDoc(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(required = true) String dataMap,
			@RequestParam(required = true) String flt,
			@RequestParam(required = true) String fileName) throws IOException {

		// 数据对象
		JSONObject rowObject = JSONObject.fromObject(dataMap);
		RowBase entity = (RowBase) JSONObject.toBean(rowObject, RowBase.class);
		if(entity.containsKey("childValues")){
			entity.remove("childValues");
		}
		if (!(rowObject.get("childValues") instanceof JSONNull)) {
			JSONObject childValuesObj = JSONObject.fromObject(rowObject.get("childValues"));
			getDataSource(childValuesObj, entity);
		}
		
//		String reportString = "招拍挂出让统计表.xls,采矿权出让情况统计表.xls";
		
		//查询统计特殊处理方法
//		if(reportString.indexOf(fileName)>-1){
//			SetReportJsonData(rowObject,entity);
//		}else if(entity!=null){
//			Set<String> keys = entity.keySet();
//			for(String key : keys){
//				Object value = entity.get(key);
//				if(value instanceof net.sf.ezmorph.bean.MorphDynaBean){
//					net.sf.ezmorph.bean.MorphDynaBean timeBean = (net.sf.ezmorph.bean.MorphDynaBean)value;
//					long time = (long)timeBean.get("time");
//					String timeString = DateUtils.convertDateToString(new Date(time));
//					entity.put(key, timeString);
//				}
//			}
//		}
		
		Configuration config = new Configuration();
		String tempPath = request.getServletContext().getRealPath("/") + "WEB-INF/freeMarkerTemp/";
		config.setDirectoryForTemplateLoading(new File(tempPath));
		config.setDefaultEncoding("UTF-8");
		
//		ClassTemplateLoader ctl = new ClassTemplateLoader(this.getClass(), "/");
//		TemplateLoader tl = config.getTemplateLoader();
//		TemplateLoader[] loaders = new TemplateLoader[] { tl, ctl };
//		MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
//		config.setTemplateLoader(mtl);

		Template t = null;
		try {
			t = config.getTemplate(flt);
		} catch (IOException e) {
			e.printStackTrace();
		}

//		String urlPath = "temp/word/";
//		String savePath = realPathResolver.get("/") + "temp/word/";
//		File dirFile = new File(savePath);
//		if (!dirFile.exists()) {
//			dirFile.mkdirs();
//		}
//		savePath += fileName;
//		urlPath += fileName;
//		
//		// 输出文档路径及名称
//		try {
//			ByteArrayOutputStream os = new ByteArrayOutputStream();
//			OutputStreamWriter osw = new OutputStreamWriter(os);
//			t.process(entity, osw);
//			String str = os.toString();
//	        
//			FileOutputStream fw = new FileOutputStream(savePath);
//			BufferedWriter bufferedWriter = new BufferedWriter(
//					new OutputStreamWriter(fw, "UTF-8"));
//			bufferedWriter.write(str);
//			bufferedWriter.flush();
//			bufferedWriter.close();
//		} catch (TemplateException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		
//		response.setHeader("Content-type", "text/html;charset=UTF-8");
//		OutputStream stream;
//		try {
//			stream = response.getOutputStream();
//			stream.write(urlPath.getBytes("UTF-8"));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		
		
		Writer out = response.getWriter();
		try {
			response.setContentType("application/x-msdownload;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
			t.process(entity, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		out.flush();
	}
	
	/**
	 * 对查询统计的json数据需要做一下特殊处理
	 * @param dataMap json数据
	 * @author 袁高磊
	 */
	
	@SuppressWarnings("unchecked")
	public void SetReportJsonData(JSONObject rowObject,RowBase entity) {
		JSONArray rowDataArray = JSONArray.fromObject(rowObject.get("data"));
		ArrayList<Map<String, String>> listObjects = new ArrayList<Map<String, String>>();
		Map<String, String> tjMap = new HashMap<String, String>();
		String tjqsj [] = rowObject.get("tjqsj").toString().split("-");
		String tjzsj []= rowObject.get("tjzsj").toString().split("-");
		tjMap.put("tjqsj_year", tjqsj[0]);
		tjMap.put("tjqsj_mon", tjqsj[1]);
		tjMap.put("tjqsj_day", tjqsj[2]);
		tjMap.put("tjzsj_year", tjzsj[0]);
		tjMap.put("tjzsj_mon", tjzsj[1]);
		tjMap.put("tjzsj_day", tjzsj[2]);
		for(int i = 0; i < rowDataArray.size(); i++){
			JSONObject jsObj = rowDataArray.getJSONObject(i);
			Iterator<String> iter = jsObj.keys();
			Map<String, String> obj = new HashMap<String, String>();
			while(iter.hasNext()){
				  String str = (String) iter.next();
				  obj.put(str, jsObj.get(str).toString());
			}
			if(obj.size()>0){
				listObjects.add(obj);
			}
		}
		entity.put("tjMap", tjMap);
		entity.put("data", listObjects);
	}
	
	/**
	 * 递归取子表
	 * 
	 * @param objs
	 * @param rowBase
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private RowBase getDataSource(JSONObject objs, RowBase rowBase) {
		JSONObject childValues = objs;
		Set<String> childTables = childValues.keySet();
		// 收集子表记录
//		HashMap<String, List<RowBase>> childHashMap = new HashMap<String, List<RowBase>>();
		for (String chidlTable : childTables) {
			List<RowBase> childRowBases = new ArrayList<RowBase>();
			JSONArray list2 = (JSONArray) childValues.get(chidlTable);
			for (int i = 0; i < list2.size(); i++) {
				JSONObject jo = (JSONObject) list2.get(i);
				RowBase childRowBase = (RowBase) JSONObject.toBean(jo, RowBase.class);
				if(childRowBase.containsKey("childValues")){
					childRowBase.remove("childValues");
				}
				// 递归取子表
				if (!(jo.get("childValues") instanceof JSONNull)) {
					JSONObject childValuesObj = JSONObject.fromObject(jo.get("childValues"));
					getDataSource(childValuesObj, childRowBase);
				}
				childRowBases.add(childRowBase);
			}
			rowBase.put(chidlTable, childRowBases);
		}
//		rowBase.setChildValues(childHashMap);
		return rowBase;
	}
}